package com.iflytek.iot.okhttp.config;

import com.iflytek.iot.common.net.NetWorkTimeout;
import com.iflytek.iot.okhttp.template.CustomerRestTemplate;
import okhttp3.ConnectionPool;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.annotation.Resource;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.util.concurrent.TimeUnit;

/**
 * @author yu 2018/12/20.
 */
@Configuration
public class RestTemplateClientConfig extends AbsRestTemplateConfig {

    @Resource
    private OkHttpConfigProperties okHttpConfigProperties;

    /**
     * 默认创建
     *
     * @return
     */
    @Primary
    @Bean
    public CustomerRestTemplate customerRestTemplate() {
        NetWorkTimeout timeout = NetWorkTimeout.builder();
        //如果为设置，则默认为1000毫秒
        timeout.setConnectTimeout(okHttpConfigProperties.getConnectTimeout());
        timeout.setReadTimeout(okHttpConfigProperties.getReadTimeout());
        timeout.setWriteTimeout(okHttpConfigProperties.getWriteTimeout());
        return super.createRestTemplate(timeout, pool());
    }

    /**
     * 使用代理模式
     *
     * @return
     */
    @Bean(name = "customerRestProxyTemplate")
    public CustomerRestTemplate customerRestProxyTemplate() {
        NetWorkTimeout timeout = NetWorkTimeout.builder();
        //如果为设置，则默认为1000毫秒
        timeout.setConnectTimeout(okHttpConfigProperties.getConnectTimeout());
        timeout.setReadTimeout(okHttpConfigProperties.getReadTimeout());
        timeout.setWriteTimeout(okHttpConfigProperties.getWriteTimeout());
        boolean usedProxy = okHttpConfigProperties.getProxy().getEnable();
        if (usedProxy) {
            return super.createRestProxyTemplate(timeout, proxy(), pool());
        }
        return super.createRestTemplate(timeout, pool());
    }

    /**
     * 创建代理
     * @return
     */
    @Bean
    public Proxy proxy() {
        String proxyHost = okHttpConfigProperties.getProxy().getHost();
        final int proxyPortNum = okHttpConfigProperties.getProxy().getPort();
        InetSocketAddress address = new InetSocketAddress(proxyHost, proxyPortNum);
        Proxy proxy = new Proxy(Proxy.Type.HTTP, address);
        return proxy;
    }


    /**
     * 创建连接池
     * @return
     */
    @Bean
    public ConnectionPool pool() {
        int maxIdleConnection = okHttpConfigProperties.getMaxIdleConnection();
        long keepAliveDuration = okHttpConfigProperties.getKeepAliveDuration();
        return new ConnectionPool(maxIdleConnection, keepAliveDuration, TimeUnit.MINUTES);
    }
}
